from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info.models import User, Category, News
from info.modules.index import index_blu

# 12)创建首页视图函数
from info.utils.response_code import RET


@index_blu.route('/newslist')
def newslist():
    """
    1.获取参数
    2.对参数进行类型转换
    3.查询所有的新闻,进行分页查询
    4.返回总页数和新闻对象
    """""
    # 1.获取参数
    page = request.args.get('page', 1)
    cid = request.args.get('cid', 1)
    per_page = request.args.get('per_page', 10)
    # 2.对参数进行类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
    # 3.查询所有的新闻, 进行分页查询
    try:
        filters = []
        if cid != "1":
            filters.append(News.category_id == cid)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据获取失败')
    # 获取到所有数据
    pages = paginate.pages
    items = paginate.items
    items = [item.to_dict() for item in items]
    # 4.返回总页数和新闻对象
    return jsonify(errno=RET.OK, errmsg='成功', totalPage=pages, newsList=items)


@index_blu.route('/', methods=['GET', 'POST'])
def index():
    # 获取到当前登录用户的id
    user_id = session.get("user_id")
    # 通过id获取用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 获取首页菜单
    try:
        category = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据获取失败')

        # 获取排行榜
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(10)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据获取失败')
    clicks_list = [news.to_dict() for news in news_clicks]

    data = {
        "user_info": user.to_dict() if user else None,
        'category': category,
        'clicks_list': clicks_list
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def get_web_lofo():
    return current_app.send_static_file("news/favicon.ico")
